<template>
  <div class="maintain-strategy-modeling">
    <el-row :gutter="20">
      <!-- 优化目标配置 -->
      <el-col :span="6">
        <el-card class="panel-card">
          <div class="panel-title">优化目标配置</div>
          <el-form label-width="80px">
            <el-form-item label="选择算法">
              <el-select v-model="form.algorithm" placeholder="请选择算法" disabled>
                <el-option label="强化学习算法" value="rl" />
              </el-select>
            </el-form-item>
            <el-form-item label="维护成本">
              <el-slider v-model="form.costWeight" :min="0" :max="100" show-input :format-tooltip="val => val + '%'" />
            </el-form-item>
            <el-form-item label="停机时间">
              <el-slider v-model="form.downtimeWeight" :min="0" :max="100" show-input :format-tooltip="val => val + '%'" />
            </el-form-item>
            <el-form-item label="设备可靠性">
              <el-slider v-model="form.reliabilityWeight" :min="0" :max="100" show-input :format-tooltip="val => val + '%'" />
            </el-form-item>
          </el-form>
          <div class="pie-chart-container">
            <pie-chart :cost="form.costWeight" :downtime="form.downtimeWeight" :reliability="form.reliabilityWeight" />
          </div>
          <el-button type="primary" block @click="confirmConfig">确认配置</el-button>
        </el-card>
      </el-col>

      <!-- 策略构建与模拟 -->
      <el-col :span="10">
        <el-card class="panel-card">
          <div class="panel-title">策略构建与模拟</div>
          <el-form label-width="90px" class="strategy-form">
            <el-form-item label="设备类型">
              <el-select v-model="strategy.deviceType" placeholder="请选择设备类型">
                <el-option label="工业设备" value="industrial" />
                <el-option label="非关键设备" value="non-critical" />
                <el-option label="关键设备" value="critical" />
              </el-select>
            </el-form-item>
            <el-form-item label="工作环境">
              <el-checkbox-group v-model="strategy.environment">
                <el-checkbox label="潮湿" />
                <el-checkbox label="高温" />
                <el-checkbox label="粉尘" />
                <el-checkbox label="振动" />
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="历史维护记录">
              <el-upload
                class="upload-demo"
                drag
                action=""
                :auto-upload="false"
                :show-file-list="true"
                :on-change="handleFileChange"
                :file-list="strategy.historyFiles"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">点击或拖拽文件上传</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="维护周期(月)">
              <el-input-number v-model="strategy.maintainPeriod" :min="1" :max="12" />
            </el-form-item>
            <el-form-item label="维护方式">
              <el-select v-model="strategy.maintainType" placeholder="请选择维护方式">
                <el-option label="预防性维护" value="preventive" />
                <el-option label="纠正性维护" value="corrective" />
                <el-option label="预测性维护" value="predictive" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="sim-btn-row">
            <el-button type="primary" @click="runSimulation">开始模拟</el-button>
          </div>
          <div v-if="simResult" class="sim-result">
            <el-divider>模拟运行</el-divider>
            <div class="sim-charts">
              <div class="sim-chart">
                <div class="sim-chart-title">成本节约趋势</div>
                <line-chart :data="simResult.costTrend" />
              </div>
              <div class="sim-chart">
                <div class="sim-chart-title">停机时间对比</div>
                <bar-chart :data="simResult.downtimeCompare" />
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 策略优化与保存 -->
      <el-col :span="8">
        <el-card class="panel-card">
          <div class="panel-title">策略优化与保存</div>
          <el-form label-width="90px">
            <el-form-item label="维护周期">
              <el-slider v-model="strategy.maintainPeriod" :min="1" :max="12" :format-tooltip="val => val + '月'" />
            </el-form-item>
            <el-form-item label="维护方式">
              <el-select v-model="strategy.maintainType" placeholder="请选择维护方式">
                <el-option label="预防性维护" value="preventive" />
                <el-option label="纠正性维护" value="corrective" />
                <el-option label="预测性维护" value="predictive" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="key-param-row">
            <div>关键参数</div>
            <div>预警阈值 <span class="param-value">80%</span></div>
            <div>响应时间 <span class="param-value">2小时</span></div>
            <div>维护窗口 <span class="param-value">周末</span></div>
          </div>
          <div class="history-title">历史模拟记录</div>
          <el-timeline class="history-list">
            <el-timeline-item
              v-for="item in historyList"
              :key="item.id"
              :timestamp="item.date"
              placement="top"
            >
              <div class="history-item">
                <span>{{ item.name }}</span>
                <span class="score">评分: {{ item.score }}</span>
                <el-button type="text" size="mini" @click="loadHistory(item)">查看</el-button>
              </div>
            </el-timeline-item>
          </el-timeline>
          <div class="save-btn-row">
            <el-button type="primary" @click="saveStrategy">保存策略</el-button>
            <el-button @click="exportReport">导出报告</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapState } from 'vuex'

// Pie chart, line chart, bar chart are simple mock components for demo
const PieChart = {
  props: ['cost', 'downtime', 'reliability'],
  render(h) {
    // Just a placeholder, not a real chart
    return h('div', {
      style: {
        width: '120px', height: '120px', margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '1px solid #eee', borderRadius: '50%'
      }
    }, [
      h('span', { style: { fontSize: '18px', color: '#409EFF' } }, `${this.cost}% / ${this.downtime}% / ${this.reliability}%`)
    ])
  }
}

const LineChart = {
  props: ['data'],
  render(h) {
    // Placeholder for line chart
    return h('div', { style: { height: '120px', border: '1px solid #eee', borderRadius: '6px', padding: '8px', textAlign: 'center' } }, [
      h('span', '趋势图（Mock）')
    ])
  }
}

const BarChart = {
  props: ['data'],
  render(h) {
    // Placeholder for bar chart
    return h('div', { style: { height: '120px', border: '1px solid #eee', borderRadius: '6px', padding: '8px', textAlign: 'center' } }, [
      h('span', '对比图（Mock）')
    ])
  }
}

export default {
  name: 'MaintainStrategyModeling',
  components: {
    PieChart,
    LineChart,
    BarChart
  },
  data() {
    return {
      form: {
        algorithm: 'rl',
        costWeight: 40,
        downtimeWeight: 30,
        reliabilityWeight: 30
      },
      strategy: {
        deviceType: 'industrial',
        environment: [],
        historyFiles: [],
        maintainPeriod: 3,
        maintainType: 'preventive'
      },
      simResult: null,
      historyList: this.getHistoryList()
    }
  },
  methods: {
    confirmConfig() {
      this.$message.success('优化目标已配置！')
    },
    handleFileChange(file, fileList) {
      this.strategy.historyFiles = fileList
    },
    runSimulation() {
      // Mock simulation logic
      const costTrend = [
        { month: '1月', value: 400 },
        { month: '2月', value: 250 },
        { month: '3月', value: 300 },
        { month: '4月', value: 350 },
        { month: '5月', value: 320 }
      ]
      const downtimeCompare = [
        { name: '方案A', value: 400 },
        { name: '方案B', value: 320 },
        { name: '方案C', value: 200 }
      ]
      this.simResult = {
        costTrend,
        downtimeCompare
      }
      this.$message.success('模拟完成，已生成评估报告！')
    },
    saveStrategy() {
      const newHistory = {
        id: Date.now(),
        name: `方案${String.fromCharCode(65 + this.historyList.length)}`,
        date: this.formatDate(new Date()),
        score: 85 + Math.floor(Math.random() * 15),
        config: JSON.parse(JSON.stringify({
          form: this.form,
          strategy: this.strategy,
          simResult: this.simResult
        }))
      }
      this.historyList.unshift(newHistory)
      this.setHistoryList(this.historyList)
      this.$message.success('策略已保存到本地！')
    },
    exportReport() {
      // Mock export: just download a JSON file
      const data = {
        form: this.form,
        strategy: this.strategy,
        simResult: this.simResult
      }
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '维护策略报告.json'
      a.click()
      URL.revokeObjectURL(url)
      this.$message.success('报告已导出！')
    },
    loadHistory(item) {
      this.form = { ...item.config.form }
      this.strategy = { ...item.config.strategy }
      this.simResult = item.config.simResult
      this.$message.info(`已加载历史方案：${item.name}`)
    },
    getHistoryList() {
      const data = localStorage.getItem('maintain_strategy_history')
      return data ? JSON.parse(data) : [
        { id: 1, name: '方案A', date: '2024-01-15', score: 92, config: {} },
        { id: 2, name: '方案B', date: '2024-01-10', score: 88, config: {} },
        { id: 3, name: '方案C', date: '2024-01-05', score: 85, config: {} }
      ]
    },
    setHistoryList(list) {
      localStorage.setItem('maintain_strategy_history', JSON.stringify(list))
    },
    formatDate(date) {
      const y = date.getFullYear()
      const m = ('0' + (date.getMonth() + 1)).slice(-2)
      const d = ('0' + date.getDate()).slice(-2)
      return `${y}-${m}-${d}`
    }
  }
}
</script>

<style scoped>
.maintain-strategy-modeling {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}
.panel-card {
  margin-bottom: 20px;
  min-height: 600px;
}
.panel-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 18px;
}
.pie-chart-container {
  margin: 24px 0 24px 0;
  display: flex;
  justify-content: center;
}
.sim-btn-row {
  text-align: right;
  margin-top: 10px;
}
.sim-result {
  margin-top: 20px;
}
.sim-charts {
  display: flex;
  gap: 20px;
}
.sim-chart {
  flex: 1;
}
.sim-chart-title {
  font-size: 14px;
  margin-bottom: 8px;
  font-weight: 500;
}
.key-param-row {
  margin: 18px 0 12px 0;
  font-size: 14px;
  color: #666;
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.param-value {
  color: #409EFF;
  margin-left: 6px;
}
.history-title {
  font-size: 15px;
  font-weight: 500;
  margin: 18px 0 8px 0;
}
.history-list {
  max-height: 180px;
  overflow-y: auto;
  margin-bottom: 16px;
}
.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.score {
  color: #67C23A;
  margin-left: 10px;
}
.save-btn-row {
  display: flex;
  gap: 12px;
  margin-top: 18px;
  justify-content: flex-end;
}
</style>
